import { useFormActions } from "@/services/useFormActions";
import * as permissionApi from "@/api/permission";
import {computed} from "vue";
import {useDataActions} from "@/services/useDataActions";


// 定义权限字段
const permissionFields = [
    'id',
    'name',
    'code',
    'type',
    'method',
    'path',
    'description'
];

// 使用通用的表单操作
export function usePermissionFormActions({ onPermissionChange = () => {} }) {
    // 使用表单控制逻辑
    const { formVisible, currentFormData, openForm } = useFormActions({
        fields: permissionFields
    })

    // 更新权限数据



    // 使用公共的数据操作逻辑
    const {  handleFormSubmit, handleDelete, handleFieldUpdate} = useDataActions({
        api: {
            add: permissionApi.createPermission,
            update: permissionApi.updatePermission,
            delete: permissionApi.deletePermission,
        },

        onActionSuccess: onPermissionChange,

        messages: {
            add: '新增权限成功',
            update: '编辑权限成功',
            delete: '删除权限成功',
            updateField: '字段更新成功'
        },
    });


    // 返回表单相关操作
    return {
        formVisible,
        currentFormData,
        openForm,
        handleFormSubmit,
        handleDelete,
        handleFieldUpdate
    };
}

//  权限列表数据
export function usePermissionListData(permissionStore, filter) {
    // 从store 中获取权限列表， 如果权限列表为空，则从API获取
    if (!permissionStore.permissionList || permissionStore.permissionList.length === 0) {
        permissionStore.fetchPermissions();
    }
    // 过滤权限列表
    const filteredPermissions = computed(() => {
        let result = permissionStore.permissionList;
        if (filter.value.name) {
            result = result.filter(item => item.name.includes(filter.value.name));
        }
        if (filter.value.code) {
            result = result.filter(item => item.code.includes(filter.value.code));
        }
        return result;
    });

    return {
        filteredPermissions
    }
}
